function sdata = scaledata(cdata, mm)
% scaleimage  - automatically scale image data for image
%
% FORMAT:       sdata = scaledata(C [, mm])
%
% Input fields:
%
%       C           MxN image data that is shown with a 256 grayscale
%       mm          min/max boundaries [default: 0, 255.999]
%
% Output fields:
%
%       sdata       scaled data (unrounded)

% Version:  v0.8a
% Build:    9103022
% Date:     Oct-30 2009, 10:52 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if ~isnumeric(cdata)
    error( ...
        'BVQXtools:BadArgument', ...
        'Invalid color data given.' ...
    );
end
if nargin < 2 || ...
   ~isa(mm, 'double') || ...
    numel(mm) ~= 2 || ...
    any(isinf(mm) | isnan(mm)) || ...
    mm(1) == mm(2)
    mm = [0, 255.999];
end
md = mm(2) - mm(1);
mmm = minmaxmean(cdata(:), 4);
sdata = mm(1) + (md / (eps + (mmm(2) - mmm(1)))) .* (double(cdata) - mmm(1));
